package com.tianyuan.lims.dms.controller.app;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianyuan.lims.common.config.paragetter.BasePageRequest;
import com.tianyuan.lims.common.config.redis.Redis;
import com.tianyuan.lims.common.config.redis.RedisManager;
import com.tianyuan.lims.common.constant.BaseConstant;
import com.tianyuan.lims.dms.entity.ZbtProductWty;
import com.tianyuan.lims.erp.admin.entity.AdminConfig;
import com.tianyuan.lims.erp.admin.entity.AdminUser;
import com.tianyuan.lims.erp.admin.service.AdminRoleService;
import com.tianyuan.lims.erp.admin.service.AdminUserService;
import com.tianyuan.lims.utils.BaseUtil;
import com.tianyuan.lims.utils.R;
import io.github.yedaxia.apidocs.ApiDoc;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
//import com.tianyuan.lims.docr4j.DDDDOcrUtil;
//import com.tianyuan.lims.docr4j.HttpUtil;


/**
 * App相关 API
 */
public class AppController extends Controller {

    @Inject
    private AdminUserService adminUserService;

    @Inject
    private AdminRoleService adminRoleService;


    public String mapshow(String stationId) {

        Integer allNum = 0;
        String title = "省生态环境监测中心";//陕西
        String province = "陕西";

//        List<String> pointDatas = new Vector<>();
//        int deptid = 2898;
//        LimsDatasource ds = dataSourceService.queryByStationId(stationId);
//        deptid = ds.getOrgId();
//        LimsArea city = LimsArea.dao.findById(deptid);
//        set("lng", city.getLng());
//        set("lat", city.getLat());
//        set("province", province);
//        province = city.getShortname();
//        List<Map<String, Object>> settings = provinceLaboratoryService.queryByStationId(stationId, deptid);
//        if (CollectionUtils.isNotEmpty(settings) && settings.size() > 0) {
//            List<Record> setting = (List<Record>) settings.get(0).get("res");
//            if (CollectionUtils.isNotEmpty(setting)) {
//                List<Record> setting1 = setting.stream().filter(s -> s.getStr("name").equals("name") && s.getStr("catg").equals("Station")).collect(Collectors.toList());
//                if (CollectionUtils.isNotEmpty(setting1)) {
//                    title = setting1.get(0).getStr("val");
//                }
//            }
//        }
//        set("province", province);
//        set("title", title + "<br>");
//        List<Map<String, Object>> data = provinceLaboratoryService.getDsPoints(deptid);
//        for (Map<String, Object> map : data) {
//            List<Record> res = (List<Record>) map.get("res");
//            for (Record record : res) {
//                pointDatas.add(JsonKit.toJson(record));
//            }
//
//        }
//        set("pointDatas", pointDatas);//
//        List<String> subStations = new Vector<>();
//        data = provinceLaboratoryService.getDssubStations(deptid);
//        List<Map<String, String>> tyData = new Vector<>();
//        List<Map<String, Object>> subData = new Vector();
//        for (Map<String, Object> map : data) {
//            List<Record> res = (List<Record>) map.get("res");
//            Integer totalNum = (Integer) map.get("totalNum");
//            for (Record record : res) {
//                String dbo = "";
//                if (record.getStr("configini") != null) {
//                    String[] reg = record.getStr("configini").split("\\\r\\\n");
//                    for (int i = 0; i < reg.length; i++) {
//                        String s1 = reg[i];
//                        if (s1.startsWith("Database_Name")) {
//                            dbo = s1.replace("Database_Name=", "");
//                            break;
//                        }
//                    }
//                    record.set("configini", dbo);
//                }
//                subStations.add(JsonKit.toJson(record));
//                Map<String, Object> subMap = new HashMap<>();
//                subMap.put("name", replaceText(record.getStr("name"), province));
//                subMap.put("value", record.get("renwunums"));
//
//                subData.add(subMap);
//                String renwus = record.getStr("renwus");
//                if (StringUtils.isNotBlank(renwus)) {
//                    String[] renwusArr = renwus.split("、");
//                    for (String r : renwusArr) {
//                        if (StringUtils.isNotBlank(r)) {
//                            String[] rd = r.split(" ");
//                            if (rd.length > 0) {
//                                Map<String, String> renwuMap = new HashMap<>();
//                                renwuMap.put("name", rd[0]);
//                                if (rd.length > 1) renwuMap.put("value", rd[1]);
//                                tyData.add(renwuMap);
//                            }
//                        }
//                    }
//                }
//            }
//            allNum += totalNum;
//        }
//        set("allNum", JsonKit.toJson(String.valueOf(allNum).split("")));
//        set("subStations", subStations);
//
//        set("subData", JsonKit.toJson(subData));//环境保护监测
//        List<String> subDataTitle = subData.stream().map(d -> d.get("name").toString()).collect(Collectors.toList());
//        set("subDataTitle", JsonKit.toJson(subDataTitle));
//        List<String> typeTitle = tyData.stream().map(d -> d.get("name")).distinct().collect(Collectors.toList());
//        List<Map<String, Object>> tyDataFinal = new Vector<>();
//        String[] color = "#b3d6dc,#2093f3,#f5845b,#c1ee42,#78e85f,#b4f171,#8fef58,#b3d6dc,#2093f3,#f5845b,#c1ee42,#78e85f,#b4f171,#8fef58".split(",");
//        int ci = 0;
//        for (String t : typeTitle) {
//            Integer tValue = tyData.stream().filter(d -> d.get("name").equals(t) && d.get("value") != null).map(d -> Integer.valueOf(d.get("value"))).mapToInt(Integer::intValue).sum();
//            Map<String, Object> typeMap = new HashMap<>();
//            //typeMap.put(t, tValue);
//            typeMap.put("name", t);
//            typeMap.put("value", tValue);
//            Map<String, String> a = new HashMap<>();
//            a.put("color", color[ci++]);
//            Map<String, Object> b = new HashMap<>();
//            b.put("normal", a);
//            typeMap.put("itemStyle", b);
//            tyDataFinal.add(typeMap);
//        }
//        set("typeTitle", JsonKit.toJson(typeTitle));
//        set("tyData", JsonKit.toJson(tyDataFinal));

        return "mapshow.html";
    }

    public static void main(String[] args) {
        try {
            //  renderJson(postResult);
        } catch (Exception e) {
//            e.printStackTrace();
            //renderJson(e.toString());
        }
    }


    // ZbtProductWty model = ZbtProductWty.dao.findById(id);

    // 主页
    public String index() {
        return "index.html";
    }

    public String agreement() {
        return "agreement.html";
    }



    // 商家-登录
    public String merchantlogin() {
        return "merchantlogin.html";
    }

    // 商家-数据录入
    public String merchantdatainput() {
        return "merchantdatainput.html";
    }

    // 商家-数据查询
    public String merchantsearch() {
        return "merchantsearch.html";
    }

    // 商家-个人信息-修改密码
    public String merchantinfo() {
        String kfdh = AdminConfig.getValue("kfdh");
        AdminUser user = BaseUtil.getUser();
        set("user", JsonKit.toJson(user));
        set("kfdh", kfdh);

        return "merchantinfo.html";
    }

    // 商家-主页
    public String merchantindex() {
        return "merchantindex.html";
    }

    public String merchantresetpass() {
        return "merchantresetpass.html";
    }


    // 客户-主页（查询）
    public String customersearch() {
        return "customersearch.html";
    }


    // 后台-主页
    public String adminindex() {
        return "adminindex.html";
    }

    // 后台-用户管理
    public String adminusermgr() {
        return "adminusermgr.html";
    }


    /**
     * @param username 手机号码
     * @param password 默认手机号码 后六位
     */
    public void loginV1(@Para("username") String username, @Para("password") String password) {

        String key = BaseConstant.USER_LOGIN_ERROR_KEY + username;
        Redis redis = RedisManager.getRedis();
        boolean enableRedis = redis == null ? false : true;
        if (enableRedis) {
            long beforeTime = System.currentTimeMillis() - 60 * 5 * 1000;
            if (redis.exists(key)) {
                if (redis.zcount(key, beforeTime, System.currentTimeMillis()) >= 15) {
                    Set zrevrange = redis.zrevrange(key, 4, 5);
                    Long time = (Long) zrevrange.iterator().next() + 60 * 5 * 1000;
                    long expire = (time - System.currentTimeMillis()) / 1000;
                    renderJson(R.error("密码错误次数过多，请等" + expire + "秒后在重试！"));
                    return;
                }
            }
            redis.zadd(key, System.currentTimeMillis(), System.currentTimeMillis());
        }
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            java.util.Map<String, Object> args = FastJson.getJson().parse(getRawData(), java.util.Map.class);
            if (args.get("username") != null) username = args.get("username").toString();
            if (args.get("username") != null) password = args.get("password").toString();
            if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
                renderJson(R.error("请输入用户名和密码！"));
                return;
            }
        }
        AdminUser user = AdminUser.dao.findFirst(Db.getSql("admin.user.queryByUserName"), username.trim());
        if (user == null) {
            //renderJson(R.error("用户名或密码错误！"));
            renderJson(R.error("未注册请联系客服"));
            return;
        }
        if (user.getStatus() == 0) {
            renderJson(R.error("账户被禁用"));
            return;
        }
        // 加上 用户过期验证
        if (user.getExpiretime() != null && user.getExpiretime().before(new Date())) {
            renderJson(R.error("账号到期请联系客服"));
            return;
        }

        if (BaseUtil.verify(username + password, user.getSalt(), user.getPassword())) {
            if (user.getStatus() == 2) {
                user.setStatus(1);
            }

            String token = IdUtil.simpleUUID();
            user.setLastLoginIp(ServletUtil.getClientIP(getRequest()));
            user.setLastLoginTime(new Date());
            user.update();
            user.setRoles(adminRoleService.queryRoleIdsByUserId(user.getUserId()));
            Integer type = getParaToInt("type", 1);

            if (enableRedis) {
                redis.del(key);
                redis.setex(token, 3600, user);
                BaseUtil.setToken(user.getUserId(), token, type);
            }

            user.remove("password", "salt");
            setSessionAttr("user", user);
            setSessionAttr("token", token);

            String kfdh = AdminConfig.getValue("kfdh");
            setSessionAttr("kfdh", kfdh);

            renderJson(
                    R.ok().put("Admin-Token", token)
                            .put("user", user)
                            .put("auth", adminRoleService.auth(user.getUserId())).put("kfdh", kfdh)
            );
        } else {
            Log.getLog(getClass()).warn("用户登录失败");
            renderJson(R.error("密码错误"));
        }

    }

    @ApiDoc(url = "/addUser", method = "post")
    public void addUser() {
        try {
            Long userId = BaseUtil.getUserId();
            if (userId == null) {
                renderJson(R.error("请先登录！"));
            }
            String data = getRawData();
            AdminUser adminUser = JSON.parseObject(data, AdminUser.class);
            adminUser.setCreateTime(new Date());
            adminUser.setUsertype(2);
            adminUser.setStatus(1);
            adminUser.setUsername(adminUser.getMobile().trim());
            adminUser.setSalt(IdUtil.simpleUUID());
            String mobile = adminUser.getMobile().trim();
            String lastSixChars = mobile.substring(Math.max(0, mobile.length() - 6));
            adminUser.setPassword(BaseUtil.sign((adminUser.getUsername().trim()
                    + lastSixChars), adminUser.getSalt()));

            Record current = null;
            List<Record> recordList = new ArrayList<>();
            if (StringUtils.isNotEmpty(mobile)) {
                recordList = Db.find("select * from crm_admin_user where usertype = 2 and mobile = ?", mobile);
            }
            if( recordList != null && !recordList.isEmpty()) {
                current = recordList.get(0);
            }
            if(current != null) {
                adminUser.setUserId(current.get("user_id"));
                adminUser.update();
                renderJson(R.ok("修改成功"));
            }else{
                if (adminUser.save()) {
                    renderJson(R.ok("修改成功"));
                } else {
                    renderJson(R.ok("修改失败"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(R.error("系统错误！"));
        }
    }

    @ApiDoc(url = "/updateUser", method = "post")
    public void updateUser() {
        String data = getRawData();
        AdminUser adminUser = JSON.parseObject(data, AdminUser.class);
//        adminUser.setSalt(IdUtil.simpleUUID());
        adminUser.setUsername(adminUser.getMobile().trim());
//        String mobile = adminUser.getMobile().trim();
//        String lastSixChars = mobile.substring(Math.max(0, mobile.length() - 6));
//        adminUser.setPassword(BaseUtil.sign((adminUser.getUsername().trim()
//                + lastSixChars), adminUser.getSalt()));
        if (adminUser.update()) {
            renderJson(R.ok("保存成功"));
        } else {
            renderJson(R.ok("保存失败"));
        }
    }


    @ApiDoc(url = "/resetPassword", method = "post")
    public void resetPassword() {
        try {
            Long userId = BaseUtil.getUserId();
            if (userId == null) {
                renderJson(R.error("请先登录！"));
            }
            String pwd = getPara("password");
            renderJson(adminUserService.resetPassword(String.valueOf(userId), pwd));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(R.error("系统错误！"));
        }
    }


    @ApiDoc(url = "/queryUserList", method = "post")
    public void queryUserList(BasePageRequest<AdminUser> basePageRequest) {
        String mobile = getPara("mobile");
        List<Record> recordList = new ArrayList<>();
        if (StringUtils.isNotEmpty(mobile)) {
            recordList = Db.find("select * from crm_admin_user where usertype = 2 and mobile = ?", mobile);
        } else {
            recordList = Db.find("select * from crm_admin_user where usertype = 2 limit 10");
        }
        renderJson(R.ok().put("data", recordList));
    }

    @ApiDoc(url = "/getUserDetailUrl", method = "post")
    public void getUserDetailUrl(BasePageRequest<AdminUser> basePageRequest) {
        try {
            String id = getPara("id");
            List<Record> recordList = new ArrayList<>();
            if (StringUtils.isNotEmpty(id)) {
                recordList = Db.find("select * from crm_admin_user where user_id = ?", id);
            }
            renderJson(R.ok().put("data", recordList));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(R.error("系统错误！"));
        }
    }


}
